{extend name="base"}
{block name="main"}
<div id="app" v-cloak>
    <el-row class="ws-quote">
        <el-col :span="10" >
            <el-button @click="onSubmit(true,'{:url(\'del\')}',{ids:checkData})" :disabled="!checkData.length" type="danger" size="small">删除</el-button>
            <el-button @click="onSubmit(true,'{:url(\'close\')}',{ids:checkData})" :disabled="!checkData.length" type="danger" size="small">启用/禁用</el-button>
            <el-button type="primary" size="small" @click="addDialog=true">添加任务</el-button>
        </el-col>
        <el-col :span="14" style="text-align: right;">
            <el-form :model="params" inline label-width="0px" size="small">
                <el-form-item>
                    <el-select v-model="params.group" placeholder="请选择分组">
                        <el-option
                          label="全部"
                          value="-1">
                        </el-option>
                        <el-option
                          :label="i.title"
                          :value="i.id.toString()" 
                          v-for="i in groups">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="params.type" placeholder="请选择状态">
                        <el-option
                          label="全部"
                          value="-1">
                        </el-option>
                        <el-option
                          label="启用"
                          value="1">
                        </el-option>
                        <el-option
                          label="禁用"
                          value="0">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="">
                    <el-button type="primary" size="mini" @click="search">查询</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
    <div class="page">{$list->render()|raw}</div>
    <el-table @selection-change="selectionChange" :data="tableData" border stripe>
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="id" label="ID" align="center" width="70" sortable></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="name" label="Name" width="100" align="center"></el-table-column>
        <el-table-column prop="action" label="Action" width="70" align="center"></el-table-column>
        <el-table-column prop="group_id" :formatter="getGroupName" label="所属分组"></el-table-column>
        <el-table-column prop="pc" label="PC管理端" width="110" align="center" sortable>
            <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.pc" size="mini">显示</el-tag>
                <el-tag type="info" v-else size="mini">隐藏</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="phone" label="移动管理端" width="120" align="center" sortable>
            <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.phone" size="mini">显示</el-tag>
                <el-tag type="info" v-else size="mini">隐藏</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="状态" sortable align="center" width="80" align="center">
            <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.status" size="mini">启用</el-tag>
                <el-tag type="info" v-else size="mini">禁用</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="功能">
            <template slot-scope="props">
                <el-tag
                  v-for="tag in props.row.options"
                  :key="tag.id"
                  size="mini"
                  class="m_x5"
                  type="success">
                  {{tag.remark}}
                </el-tag>
            </template>
        </el-table-column>
        
        <el-table-column label="操作">
            <template slot-scope="scope">
                <el-button type="danger" size="mini" class="ws-mini" @click="onGet('{:url(\'del\')}?id='+scope.row.id,true)">删除</el-button>

                <el-button type="danger" size="mini" class="ws-mini" @click="close(scope.row)" v-if="scope.row.status">禁用</el-button>
                <el-button type="primary" size="mini" class="ws-mini" @click="close(scope.row)" v-else>启用</el-button>

                <el-button type="primary" size="mini" class="ws-mini" @click="edit(scope.row)">编辑</el-button>
                <el-button type="primary" size="mini" class="ws-mini" @click="showFuncTransfer(scope.row)">分配功能</el-button>
                <el-button type="primary" size="mini" class="ws-mini" @click="showFuncParams(scope.row)">编辑功能属性</el-button>
                
                <el-button type="warning" size="mini" class="ws-mini" v-if="scope.$index>0" icon="el-icon-arrow-up" @click="upRecord(scope.$index)"></el-button>

                <el-button type="warning" size="mini" class="ws-mini" v-if="scope.$index<tableData.length-1" icon="el-icon-arrow-down" @click="downRecord(scope.$index)"></el-button>
            </template>
        </el-table-column>
    </el-table>
    <div class="page">{$list->render()|raw}</div>

    <!-- 添加、编辑分组 start -->
    <el-dialog :title="dialogTitle" width="500px" :visible.sync="addDialog">
        <el-form ref="forms" :model="data" :rules="rules" label-width="80px">
            <el-form-item label="标题" prop="title">
                <el-input v-model="data.title" placeholder="标题"></el-input>
            </el-form-item>
            <el-form-item label="name" prop="name">
                <el-input v-model="data.name" placeholder="name(英文,移动端识别唯一码)"></el-input>
            </el-form-item>
            <el-form-item label="action" prop="action">
                <el-input v-model="data.action" placeholder="action(分组下识别任务唯一码)"></el-input>
            </el-form-item>
            <el-form-item label="所属分组" prop="group_id">
                <el-select v-model="data.group_id" placeholder="请选择分组">
                    <el-option
                      v-for="item in groups"
                      :key="item.id"
                      :label="item.title+'('+item.event+')'"
                      :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="Icon" prop="icon">
                <el-input v-model="data.icon" placeholder="图标（图标name）"></el-input>
            </el-form-item>
            <el-form-item label="PC管理端" prop="pc">
                <el-radio-group v-model="data.pc">
                    <el-radio :label="0">隐藏</el-radio>
                    <el-radio :label="1">显示</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="移动端" prop="phone">
                <el-radio-group v-model="data.phone">
                    <el-radio :label="0">隐藏</el-radio>
                    <el-radio :label="1">显示</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="data.status">
                    <el-radio :label="0">禁用</el-radio>
                    <el-radio :label="1">启用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="任务记录" prop="type">
                <el-radio-group v-model="data.type">
                    <el-radio :label="0">保存</el-radio>
                    <el-radio :label="1">不保存</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="addDialog = false">取 消</el-button>
            <el-button type="primary" @click="onSubmit('forms','{:url(\'add\')}',submitData)">提 交</el-button>
        </div>
    </el-dialog>
    <!-- 添加、编辑分组 end -->

    <!-- 分配功能 start -->
    <el-dialog :title="funcSelectTitle" width="600px" :visible.sync="showFuncSelect">
        <el-transfer
            v-model="func"
            :filterable="false"
            :props="props"
            :titles="['未选功能','已选功能']"
            @change="transferChange"
            :data="funcs">
            
        </el-transfer>
    </el-dialog>
    <!-- 分配功能 end -->

    <!-- 编辑功能属性 start -->
    <el-dialog :title="funcParamsDialogTitle" width="800px" :visible.sync="showFuncParamsDialog">
        <el-tabs tab-position="left" v-if="showFuncParamsDialog">
            <el-tab-pane :label="item._title" v-for="(item,key) in currentTask.params">
                <p style="background-color: #eee;line-height: 40px;padding: 0 20px;">功能属性设置：</p>
                <el-form :model="item" label-width="80px">
                    <el-form-item label="是否开启" v-if="item.show">
                        <el-radio-group v-model="item.show">
                            <el-radio label="false">否</el-radio>
                            <el-radio label="true">是</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="是否多条" v-if="item.mult">
                        <el-radio-group v-model="item.mult">
                            <el-radio label="false">否</el-radio>
                            <el-radio label="true">是</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="分类限定" v-if="item.media_type">
                        <el-radio-group v-model="item.media_type.val">
                            <el-radio :label="v" v-for="v in item.media_type.option">{{v}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item :label="item._title" v-if="item.default!==undefined">
                        <el-input v-model="item.default" :placeholder="item._title"></el-input>
                    </el-form-item>
                    <el-form-item label="placeholder" v-if="item.placeholder!==undefined">
                        <el-input v-model="item.placeholder" placeholder="占位符"></el-input>
                    </el-form-item>
                    <el-form-item label="功能标题" v-if="item.title!==undefined">
                        <el-input v-model="item.title" placeholder="功能标题"></el-input>
                    </el-form-item>
                    <el-form-item label="账号类型" v-if="item.mine">
                        <el-radio-group v-model="item.mine.val">
                            <el-radio :label="v" v-for="v in item.mine.option">{{v}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="导入Excel" v-if="item.excel">
                        <el-radio-group v-model="item.excel">
                            <el-radio label="false">否</el-radio>
                            <el-radio label="true">是</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="开启地图" v-if="item.map">
                        <el-radio-group v-model="item.map">
                            <el-radio label="false">否</el-radio>
                            <el-radio label="true">是</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>
        <div slot="footer" class="dialog-footer">
            <el-button @click="showFuncParamsDialog = false">取 消</el-button>
            <el-button type="primary" @click="_wspost('{:url('grantFunc')}',{id:currentTask.id,params:currentTask.params,options:-1})">提 交</el-button>
        </div>
    </el-dialog>
    <!-- 编辑功能属性 end -->
</div>
{/block}

<!--------------------------分割线------------------------>
<!--------------------------分割线------------------------>
<!--------------------------分割线------------------------>

{block name="vue"}
<script>
var app=new Vue({
    el:"#app",
    mixins:[wsMixins],
    data:{
        groups:{$groups->toJson()|raw},
        tableData:{$list->toJson()|raw}, // 列表数据
        checkData:[], // 选中数据
        params:{$params|json_encode|raw},
        imagesPrefix:"{:images('')}",
        data:{}, // 添加、编辑数据
        addDialog:false, // 显示添加、编辑框
        dialogTitle:'添加分组', // 添加、编辑框标题
        rules:{
            title:{required:true,message:'标题不能为空'},
            name:{required:true,message:'Name不能为空'},
            action:{required:true,message:'Action不能为空'},
            group_id:{required:true,message:'请选择分组'},
            icon:{required:true,message:'图标不能为空'},
        },

        // 穿梭框(分配功能)
        showFuncSelect:false,
        funcSelectTitle:'分配功能',
        currentTask:null, //当前操作的 Row (编辑功能属性中也适用该项)
        funcs:{$funcs->toJson()|raw},
        props:{key:'id',label:'remark'},
        func:[], //选中的

        //编辑功能属性
        showFuncParamsDialog:false,
        funcParamsDialogTitle:'编辑功能属性',
    },
    created(){
        this.emptyData();
    },
    computed:{
        submitData(){
            return Object.assign(this.data,{
            });
        },

    },
    watch:{
        addDialog(val){
            if(!val){
                this.dialogTitle='添加分组';
                this.emptyData();
            }
        },
    },
    methods:{
        // 用户选择发生改变
        selectionChange(data){
            this.checkData=data.map(item=>{
                return item.id;
            })
        },
        emptyData(newData={}){
            this.data=Object.assign({
                title:'',
                name:'',
                action:'',
                status:1,
                type:1,
                pc:1,
                phone:1,
                group_id:null,
            },this.clone(newData));
        },
        // 素材组编辑
        edit(row){
            this.emptyData(row);
            this.dialogTitle='分组编辑';
            this.addDialog=true;
        },
        // 格式化数据 返回任务容器所属分组
        getGroupName(row,col,val,index){
            let groups=this.groups;
            for(i in groups){
                let item=groups[i];
                if(item.id==val){
                    return item.title+'('+item.event+')';
                }
            }
        },
        // 素材组启用、禁用
        close(row){
            this._wspost("{:url('close')}",{id:row.id},res=>{
                if(res.code){
                    row.status=Math.abs(row.status-1);
                }
            },false);
        },
        // 上移
        upRecord(i){
            let props=this.tableData;
            if(i<1)return;
            let t1=props[i],t2=props[i-1];
            let data=[
                {id:t1.id,sort:t2.sort},
                {id:t2.id,sort:t1.sort},
            ];
            $.post("{:url('record')}",{val:data},res=>{
                if(typeof res==='string'){
                    res=JSON.parse(res);
                }
                if(res.code!==0){
                    let temp=t1.sort;
                    t1.sort=t2.sort;t2.sort=temp;
                    props.splice(i-1,2,t1,t2);
                }else if(res.code===0&&res.msg){
                    this.$message({
                        message:res.msg,
                        type:'error'
                    })
                }
            })
            
        },
        // 下移
        downRecord(i){
            let props=this.tableData;
            if(i===props.length){
                return;
            }
            let t1=props[i+1],t2=props[i];
            let data=[
                {id:t1.id,sort:t2.sort},
                {id:t2.id,sort:t1.sort},
            ];
            $.post("{:url('record')}",{val:data},res=>{
                if(typeof res==='string'){
                    res=JSON.parse(res);
                }
                if(res.code!==0){
                    let temp=t1.sort;
                    t1.sort=t2.sort;t2.sort=temp;
                    props.splice(i,2,t1,t2);
                }else if(res.code===0&&res.msg){
                    this.$message({
                        message:res.msg,
                        type:'error'
                    })
                }
            })
            
        },
        // 打开分配功能框
        showFuncTransfer(row,isShow=true){
            if(row.params&&typeof row.params==='string'){
                row.params=JSON.parse(row.params);
            }
            if(row.title){
                this.funcSelectTitle='分配功能（'+row.title+'）';
            }else{
                this.funcSelectTitle='分配功能';
            }
            this.currentTask=row;
            this.showFuncSelect=isShow;
            this._initCheckFunc(row.options);
        },
        // 为任务容器分配功能
        transferChange(rightVal,direction,val){
            let funcs=this.funcs,
                currentTask=this.currentTask;
            let defaultOptions=this.clone(currentTask.options);
            let oldParams=this.clone(currentTask.params);
            currentTask.options=[];
            funcs.forEach(item=>{
                if(rightVal.indexOf(item.id)>=0){
                    currentTask.options.push(item);
                }
            });
            // params是简化版的 urrentTask.options 属性（提炼需要的数据）
            let params=this._formatParams(currentTask.options,currentTask.title);
            if(oldParams){
                params=this._merge(oldParams,params);
            }
            this._wspost("{:url('grantFunc')}",{id:currentTask.id,options:currentTask.options,params},res=>{
                if(!res.code){
                    // 失败还原
                    currentTask.options=defaultOptions;
                    this._initCheckFunc(defaultOptions);
                }else{
                    currentTask.params=params;
                }
            },false);
        },
        // 合成新数据，保留旧的配置项
        _merge(a,b){
            let n;
            if(b&&typeof b==='object'&&!Array.isArray(b)){
                n={}
                for(let i in b){
                    if(typeof a[i]==='undefined'||typeof b[i]==='undefined'){
                        n[i]=b[i];
                    }else{
                        n[i]=this._merge(a[i],b[i]);
                    }
                }
            }else if(a.toString()!==b.toString()){
                n=a;
            }else{
                n=b;
            }
            return n;
        },
        //提炼实际属性（简化繁琐的配置项）
        _formatParams(o,title){
            if(!o||!Array.isArray(o)){
                return {};
            }
            let rs={};
            o.forEach(item=>{
                let row={_title:item.remark};
                item.taskparams.forEach(v=>{
                    if(item.key==='title'&&v.key==='default'){
                        v.value=title;
                    }
                    if(v.option&&v.option.length){
                        row[v.key]={val:v.value,option:v.option.split('|')};
                    }else{
                        row[v.key]=v.value;
                    }
                })
                rs[item.key]=row
            });
            return rs;
        },
        // 初始化穿梭框选中数据
        _initCheckFunc(o){
            this.func=[];
            o.forEach(item=>{
                this.func.push(parseInt(item.id));
            });
        },
        //编辑功能属性
        showFuncParams(row,isShow=true){
            if(row.params&&typeof row.params==='string'){
                row.params=JSON.parse(row.params);
            }
            if(row.title){
                this.funcParamsDialogTitle='编辑功能属性（'+row.title+'）';
            }else{
                this.funcParamsDialogTitle='编辑功能属性';
            }
            this.currentTask=row;
            this.showFuncParamsDialog=isShow;
        },
        // 搜索查询
        search(){
            let params=this.params,queryStr='';
            for(let key in params){
                if(queryStr.length>0){
                    queryStr+='&';
                }else{
                    queryStr+='?';
                }
                queryStr+=key+'='+params[key];
            }
            location.href="{:url('')}"+queryStr;
        },
    },
});
</script>
{/block}